package com.ys.servers.common.mq;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.MessageCodec;
import io.vertx.core.json.JsonObject;

import java.nio.ByteBuffer;

/**
 * Created by taotao on 2017/2/23.
 */
public class EventBusCodec implements MessageCodec<InternalEventData, InternalEventData> {

    private InternalEventData internalEventData;

    @Override
    public void encodeToWire(Buffer buffer, InternalEventData internalEventData) {
        this.internalEventData = internalEventData;
        buffer.appendBytes(internalEventData.encode());
    }

    @Override
    public InternalEventData decodeFromWire(int i, Buffer buffer) {
        //   internalEventData.decode(buffer.getBytes());
        ;
        //buffer.getBytes(,buffer.length());
        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.getBytes(i,buffer.length()));
        int l1 = byteBuffer.getInt();
        int l2 = byteBuffer.getInt();
        int l3 = byteBuffer.getInt();
        byte[] t1 = new byte[l1];
        byte[] t2 = new byte[l2];
        byte[] t3 = new byte[l3];
        byteBuffer.get(t1);
        byteBuffer.get(t2);
        byteBuffer.get(t3);
        internalEventData = new InternalEventData();
        internalEventData.setRecordAddress(new String(t1)).setApiName(new String(t2)).setParas(new JsonObject(new String(t3)));
        return internalEventData;
    }

    @Override
    public InternalEventData transform(InternalEventData socketData) {
        return socketData;
    }

    @Override
    public String name() {
        return "socket_data_codec";
    }

    @Override
    public byte systemCodecID() {
        return -1;
    }
}
